<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>

<body>
  <form action="https://www.imooc.com/api/http/search/suggest?words=js" method="POST" id="login"
    enctype="application/x-www-form-urlencoded">
    <input type="text" name="username">
    <input type="passowrd" name="password">
    <input type="submit" id="btn" value="登录">
  </form>
  <script>
    const login = document.getElementById('login')
    const btn = document.getElementById('btn')
    btn.onclick = function (e) {
      //阻止表单自动提交
      e.preventDefault()
      const url = 'https://www.imooc.com/api/http/search/suggest?words=js';
      const xhr = new XMLHttpRequest
      xhr.onload = () => {
        if (xhr.readyState !== 4) return;
        if ((xhr.status >= 200 && xhr.status < 300) || xhr.status === 304) {
          console.log(xhr.responseText);
          // console.log(typeof xhr.responseText);
        }
      }
      xhr.open('POST', url, true)
      //可用于发送表单数据
      const data=new FormData(login)
      //通过append()方法添加数据
      data.append('age',18)
     /*  for(let item of login){
        console.log(item);
      } */
      // xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded')
      // const data=`username=${login.username.value}&password=${login.password.value}`
      xhr.send(data)
    }
  </script>
</body>

</html>